package com.pocket.insight.base.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * 描述：
 *
 * @author shuize
 * @create 2024/12/10
 */
@Slf4j
public class JSONUtil {

    private static final DateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static <T> T toJavaObject(String json, Class<T> clazz) {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(json);
        return JSON.toJavaObject(jsonObject, clazz);
    }

    public static String toJSONString(Object object) {
        if (object == null) {
            return "";
        }
        return JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect);
    }


    public static <T> T toJavaObjectNicely(String json, Class<T> clazz) {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        T rtnObj = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(DEFAULT_DATE_FORMAT);
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            rtnObj = (T)mapper.readValue(json, clazz);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return rtnObj;
    }

    public static <T> T deepCopy(T other) {
        if (other == null) {
            return null;
        }
        try {
            return (T) toJavaObject(toJSONString(other), (Class)other.getClass());
        } catch (Exception e) {
            e.printStackTrace();
            return (T) toJavaObjectNicely(toJSONStringNicely(other), (Class)other.getClass());
        }
    }

    public static String toJSONStringNicely(Object object) {
        ObjectMapper mapper = getDefaultSerializationJacksonMapper();
        return toJSONStringNicely(mapper, object);
    }


    public static String toJSONStringNicely(ObjectMapper objectMapper, Object object) {
        if (object == null) {
            return "";
        }
        ObjectMapper mapper = objectMapper;
        if (mapper == null) {
            mapper = new ObjectMapper();
        }
        try {
            return mapper.writeValueAsString(object);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "";
        }
    }

    protected static ObjectMapper getDefaultSerializationJacksonMapper() {
        ObjectMapper mapper = new ObjectMapper();
        return mapper;
    }

}
